package com.controller;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.google.gson.Gson;
import com.pojo.Account;
import com.service.AccountService;
import org.apache.tomcat.util.json.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

@RestController
public class AccountController {
    @Autowired
    AccountService accountService;

    @Autowired
    Gson gson;

    @RequestMapping("/find/{val}")
    public Account findById(@PathVariable("val") int id){
        return accountService.findAccountById(id);
    }


    @RequestMapping(value = "/find/get", method = RequestMethod.GET)
    @CrossOrigin
    public Account findByIdGet(@RequestParam("id") int id){
        return accountService.findAccountById(id);
    }

    @RequestMapping(value = "/find/post", method = RequestMethod.POST)
    @CrossOrigin
    public Account findByIdPost(@RequestParam(value = "id", required = true) int id, HttpServletResponse response){
//        @CrossOrigin 即可
//        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Access-Control-Allow-Methods", "POST");
//        response.setIntHeader("Access-Control-Max-Age", 1000);
        return accountService.findAccountById(id);
    }

    @RequestMapping(value = "/find/jsonp")
    @CrossOrigin
    public String findByIdJsonP(@RequestParam(value = "id", required = true) int id,
                                @RequestParam(value = "callback", required = true) String callback){
        //变相的实现JSONP
        Account account = accountService.findAccountById(id);
        return callback+"("+gson.toJson(account)+")";
    }
}
